// import "./main.js";
// ===============================变量定义==============================
/**图片数组 */
var index = 0;
// 数组用
const IMG_PAGE = new Array();
IMG_PAGE[0] = "../img/1.jpg";
IMG_PAGE[1] = "../img/2.jpg";
IMG_PAGE[2] = "../img/3.jpg";
IMG_PAGE[3] = "../img/4.jpg";
IMG_PAGE[4] = "../img/5.jpg";
IMG_PAGE[5] = "../img/6.jpg";
IMG_PAGE[6] = "../img/7.jpg";
IMG_PAGE[7] = "../img/8.jpg";
IMG_PAGE[8] = "../img/9.jpg";
IMG_PAGE[9] = "../img/10.jpg";
IMG_PAGE[10] = "../img/11.jpg";
IMG_PAGE[11] = "../img/12.jpg";
IMG_PAGE[12] = "../img/13.jpg";
IMG_PAGE[13] = "../img/14.jpg";
IMG_PAGE[14] = "../img/15.jpg";
IMG_PAGE[15] = "../img/16.jpg";
IMG_PAGE[16] = "../img/17.jpg";
IMG_PAGE[17] = "../img/18.jpg";
IMG_PAGE[18] = "../img/19.jpg";
IMG_PAGE[19] = "../img/20.jpg";
IMG_PAGE[20] = "../img/21.jpg";


/**@type {HTMLCanvasElement} */
const $canvas = document.querySelector("#page");
const ctx = $canvas.getContext("2d");

/** 用于暂存下一章图片的canvas
 * @type {HTMLCanvasElement} */
const $hiddencanvas = document.querySelector("#hiddencanvas");
const ctx2 = $hiddencanvas.getContext('2d');

const WIDTH = 360;
const HEIGHT = 240;

$canvas.width = WIDTH;
$canvas.height = HEIGHT;

$hiddencanvas.width = WIDTH;
$hiddencanvas.height = HEIGHT;


// 图片
/**当前图 */
const $img = new Image(WIDTH, HEIGHT);
$img.crossOrigin = "anonymous";
$img.src = IMG_PAGE[0];

/**下一张图 */
const $nextimg = new Image(WIDTH, HEIGHT);
$nextimg.crossOrigin = "anonymous";
$nextimg.src = IMG_PAGE[index + 1];

/**翻转的时候折点坐标 */
let offsetX;
let offsetY;
/**循环动画的interval */
let interval;
/**判断是否跳转到下一个图片 */
let next = false;

/**用于处理下一章图片时候加载好 */
var first = false;

/**存放下一章图片翻页时候对应位置的图像像素 */
var nextImageDate;
var imgData;
/**翻页的时候翻页在空中的图片的图像数据 */
var newImgData;

// ==============================函数定义=================================

/**按下图片的时候鼠标操作 */
function onmouseclick() {
  if (first == true) {
    console.log(index);
    offsetX = $canvas.width;
    offsetY = $canvas.height;
    next = false;
    if (typeof bottomX !== "undefined") {
      bottomX = 0;
    }
    if (interval !== "undefined") {
      clearInterval(interval);
    }
    if (index < IMG_PAGE.length - 1)
      interval = setInterval(turnToPage, 1000 / 24);
    else
      alert("已经是最后一张了哦");
  } else {
    console.log("第一章图片加载失败");
  }
}

/**翻页功能具体实现 */
function turnToPage() {
  // const offsetX = clamp(e.offsetX, 0, WIDTH - 1);
  // const offsetY = clamp(e.offsetY, 0, HEIGHT - 1);
  offsetX -= $canvas.width / 24;
  offsetY -= $canvas.height / 24;

  ctx.clearRect(0, 0, $canvas.width, $canvas.height);
  // ClearCanvas($canvas);

  // 两点连线的角度
  const beta = Math.atan2(HEIGHT - offsetY, WIDTH - offsetX);

  const tanBeta = Math.tan(beta);
  const sinBeta = Math.sin(beta);

  // 两点连线m的长度
  const len = (HEIGHT - offsetY) / sinBeta;

  // 过点[offsetX, offsetY]作连线的垂线，交下边于点[bottomX, bottomY]，bottomX >=0，过点[bottomX,bottomY]作直线m的垂线n，交上边或右边于点[topX,topY]。
  // 点[bottomX, bottomY]与点[topX,topY]是模拟翻页时的折线
  const bottomY = HEIGHT;
  let bottomX = offsetX - (bottomY - offsetY) * tanBeta;
  // console.log(bottomX);
  if (bottomX < 0) {
    bottomX = 0;
    next = true;
  }

  let topY = 0;
  let topX = bottomX + HEIGHT * tanBeta;
  if (topX > WIDTH) {
    topX = WIDTH;
    topY = bottomY - (WIDTH - bottomX) / tanBeta;
  }

  // [topX,topY]和[bottomX,bottomY]两点连线l与水平线的夹角
  const theta = Math.atan2(bottomY - topY, bottomX - topX) - Math.PI / 2;
  const sinTheta = Math.sin(theta);
  const cosTheta = Math.cos(theta);
  // 直线l的斜率
  const slope = (bottomX - topX) / (bottomY - topY);

  if (typeof nextImageDate !== "undefined")
    drawCurlPage();
  // 画辅助线
  // drawHelperLines();

  function drawCurlPage() {
    for (let y = 0; y < HEIGHT; y++) {
      // 与直线l的x交点，l左边是没有卷曲的部分，右边是卷曲的部分，分开处理。
      const crossX = bottomX - (bottomY - y) * slope;
      const endX = crossX >> 0;
      // 直线l左边
      for (let x = 0; x < endX; x++) {
        const pos = (y * WIDTH + x) * 4;
        newImgData.data[pos] = imgData.data[pos];
        newImgData.data[pos + 1] = imgData.data[pos + 1];
        newImgData.data[pos + 2] = imgData.data[pos + 2];
        newImgData.data[pos + 3] = imgData.data[pos + 3];
      }
      // 直线l右边
      for (let x = endX; x <= WIDTH; x++) {
        const pos = (y * WIDTH + x) * 4;

        const dx = x - crossX;
        const d = dx * cosTheta;
        // 当rate>0.5时，说明当前像素点映射在背面。
        // const rate = d / len;

        // 页面下的阴影
        const opacity = ((len - d) / len) * 255;
        // console.log(nextImageDate[pos],imgData[pos]);
        newImgData.data[pos] = nextImageDate.data[pos];
        newImgData.data[pos + 1] = nextImageDate.data[pos + 1];
        newImgData.data[pos + 2] = nextImageDate.data[pos + 2];
        // newImgData.data[pos + 3] = opacity;
        newImgData.data[pos + 3] = nextImageDate.data[pos + 3];

        // 算出点在半圆映射中的位移，其中半圆的周长为len
        // y=x 与 y=len/π·sin(πx/len) 相减得到offset。即点映射的位移
        const offset = d - Math.sin((Math.PI * d) / len) * (len / Math.PI);
        const targetX = (x - offset * cosTheta + 0.5) >> 0;
        const targetY = (y - offset * sinTheta + 0.5) >> 0;

        const targetPos = (targetY * WIDTH + targetX) * 4;

        // 页面加上简易的阴影，加强立体效果
        // const gray = rate <= 0.5 ? -127 * rate : 127 * (rate - 0.5);

        newImgData.data[targetPos] = imgData.data[pos];
        newImgData.data[targetPos + 1] = imgData.data[pos + 1];
        newImgData.data[targetPos + 2] = imgData.data[pos + 2];
        newImgData.data[targetPos + 3] = imgData.data[pos + 3];

        // 在像素点旋转映射的时候会有漏点，做个强行插值
        newImgData.data[targetPos + 4] = imgData.data[pos];
        newImgData.data[targetPos + 5] = imgData.data[pos + 1];
        newImgData.data[targetPos + 6] = imgData.data[pos + 2];
        newImgData.data[targetPos + 7] = imgData.data[pos + 3];
        // newImgData.data[targetPos + 8] = imgData.data[pos] + gray;
        // newImgData.data[targetPos + 9] = imgData.data[pos + 1] + gray;
        // newImgData.data[targetPos + 10] = imgData.data[pos + 2] + gray;
        // newImgData.data[targetPos + 11] = imgData.data[pos + 3];
      }
    }

    ctx.putImageData(newImgData, 0, 0);
    // ctx.restore();
    if (next) {

      ClearCanvas($canvas);
      clearInterval(interval);
      offsetX = $canvas.width;
      offsetY = $canvas.height;
      next = false;
      if (index < IMG_PAGE.length)
        index++;
      $img.src = IMG_PAGE[index];
      $img.onload = function () {
        ctx.drawImage($img, 0, 0, WIDTH, HEIGHT);
        imgData = ctx.getImageData(0, 0, WIDTH, HEIGHT);
      }

      if (index != IMG_PAGE.length - 1) {
        $nextimg.src = IMG_PAGE[index + 1];
        $nextimg.onload = function () {
          ctx2.drawImage($nextimg, 0, 0, WIDTH, HEIGHT);
          nextImageDate = ctx2.getImageData(0, 0, WIDTH, HEIGHT);
        }
      }

    }
  }
}

/**初始化的时候图片加载好调用的 */
function start() {
  // ctx.save();
  ctx.drawImage($img, 0, 0, WIDTH, HEIGHT);

  /*
    data: Uint8ClampedArray
    图片像素数据,每个像素占4个值
    [R,G,B,A,R,G,B,A...]
   */
  imgData = ctx.getImageData(0, 0, WIDTH, HEIGHT);
  newImgData = ctx.createImageData(WIDTH, HEIGHT);
  $nextimg.onload = function () {
    ctx2.drawImage($nextimg, 0, 0, WIDTH, HEIGHT);
    // $hiddencanvas.style.visibility = "visible";
    first = true;
    nextImageDate = ctx2.getImageData(0, 0, WIDTH, HEIGHT);
  }

  // $canvas.addEventListener("mousemove", onMouseMove);
  $canvas.onmousedown = onmouseclick;
}

function clamp(num, min = num, max = num) {
  return Math.min(max, Math.max(min, num));
}

/**初始化 */
function init() {
  $img.onload = start;
}


// ========================初始化========================

init();